<!DOCTYPE html>
<html lang="en">

<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>Document</title>
  <link rel="stylesheet" href="https://unpkg.com/element-ui/lib/theme-chalk/index.css">
</head>

<body>
  <div id="app">
    <el-tree ref="tree" :data="data" :props="defaultProps" @node-click="handleNodeClick"
      @node-expand="handleNodeExpand"></el-tree>
  </div>

  <script src="https://cdn.bootcdn.net/ajax/libs/vue/2.6.9/vue.min.js"></script>
  <script src="https://unpkg.com/element-ui/lib/index.js"></script>
  <script>
    let addId = 3;
    new Vue({
      el: '#app',
      data() {
        return {
          data: [
            { label: '一级 1', id: 1, children: [] },
            { label: '一级 2', id: 2, children: [] },
          ],
          defaultProps: {
            children: 'children',
            label: 'label'
          }
        };
      },
      methods: {
        // falg:是否强制加载
        loadChildren(parentNode, falg = false) {
          setTimeout(() => {
            let num = Math.ceil(Math.random() * 10);
            if ([2, 4, 6].includes(num) && !falg) {
              this.$message('未获取到子元素');
              this.$set(parentNode, 'children', []);
            } else {
              const newChildren = new Array(num).fill(1).map((item, index) => {
                addId++;
                return {
                  label: `laebel ${addId}`,
                  id: addId
                };
              });
              this.$set(parentNode, 'children', newChildren);
              console.log(parentNode);
              this.$refs.tree.store.nodesMap[parentNode.id].expanded = true;
              parentNode.unfold = true;
            }
          }, 1000);
        },
        handleNodeExpand(parentNode) {
          this.$set(parentNode, 'children', []);
          if (parentNode.expanded) {
          } else {
            this.loadChildren(parentNode, true);// 加载子级
          }
        },
        handleNodeClick(parentNode) {
          console.log(67, parentNode);
          this.$set(parentNode, 'children', []);
          this.loadChildren(parentNode);// 加载子级
        }
      }
    });

  </script>
</body>

</html>